package com.sansui.blog.controller;

import com.sansui.blog.pojo.Comment;
import com.sansui.blog.pojo.SysConfig;
import com.sansui.blog.pojo.User;
import com.sansui.blog.pojo.UserInfo;
import com.sansui.blog.service.BlogService;
import com.sansui.blog.service.CommentService;
import com.sansui.blog.service.SysInfoService;
import com.sansui.blog.service.UserInfoService;
import com.sansui.blog.utils.IpUtil;
//import com.sun.istack.internal.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @name: CommentController
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-04-27 23:14
 **/
@Controller
@RequestMapping("/blogs")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SysInfoService sysInfoService;

    /**
     * 获取评论信息
     *
     * @param blogId
     * @param model
     * @return
     */
    @GetMapping("/comments/{blogId}")
    public String getComments(@PathVariable Long blogId,Model model) {
        SysConfig sysConfig = sysInfoService.getSysSetting();
        List<Comment> comments = commentService.listCommentByBlogId(blogId);
        model.addAttribute("comments", comments);
        model.addAttribute("commentNum", commentService.getCommentCountByBlogId(blogId));
        return "theme/"+ sysConfig.getThemeName() +"/blog :: commentList";
    }

    /**
     * 保存评论信息
     *
     * @param comment
     * @return
     */
    @PostMapping("/comments")
    public String saveComments(Comment comment, HttpServletRequest request, HttpSession session) {

//        User user = (User) session.getAttribute("user");
        Map<String,Object> data = (Map<String, Object>) session.getAttribute("user");
        if (data != null) {
            UserInfo userInfo = userInfoService.getUserInfoByUserId(String.valueOf(data.get("uid")));
            comment.setAvatar(userInfo.getAvatars());
            comment.setAdmincomment(1);
        }
        String ipAddress = IpUtil.getIpAddr(request);
        comment.setCommentlocation(ipAddress);
        commentService.saveComments(comment);
        commentService.sendEmail(comment.getBlogId(),comment.getComment(),comment.getParentcommentid(),comment.getNickname(),comment.getUrl());
        return "redirect:/blogs/comments/" + comment.getBlogId();
    }

}
